package com.oss.util;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author chengqiang
 * 下载工具类
 */
@Data
@Component
@Slf4j
public class DownloadUtil {
    @Autowired
    ZipUtils zipUtils;
    @Autowired
    HttpServletResponse response;

    /**
     * 下载文件 , 入参为文件路径 , 并以流的形式响应
     * @param fileText      待写出的文件内容
     * @param fileName      文件名称
     */
    public void downloadFile(String fileText, String fileName) {
        OutputStream outputStream = null;
        try {
            if(StringUtils.isEmpty(fileText)){
                fileText = "";
            }
            outputStream = response.getOutputStream();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
            byte[] buffer = new byte[4096];
            outputStream.write(fileText.getBytes());
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {

            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
    /**
     * 下载文件 , 入参为文件输入流 , 并以流的形式响应
     * @param inputStream   excel文件输入流
     * @param fileName      文件名称
     */
    public void downloadFile(InputStream inputStream, String fileName) {
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
            byte[] buffer = new byte[4096];
            int length;
            while ((length=inputStream.read(buffer))!=-1) {
                outputStream.write(buffer,0,length);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }

    /**
     * 压缩包下载
     * @param filePathList  文件列表
     * @param fileName      zip文件名称
     * @param deleteSourceFile      是否删除原文件
     */
    public void downloadZipFile(List<String> filePathList, String fileName,boolean deleteSourceFile) throws Exception {
        if (CollectionUtils.isNotEmpty(filePathList)) {
            zipUtils.fileToZip(filePathList,fileName);
            if (deleteSourceFile == true) {
                filePathList.forEach(filePath->deleteFileAndDir(filePath));
            }
        }
    }

    /**
     * 删除文件件/文件
     * @param filePath 文件路径
     */
    public void deleteFileAndDir(String filePath){
        File file = new File(filePath);
        if (file.exists()) {
            // 文件夹
            if (file.isDirectory()){
                File[] files = file.listFiles();
                if (files != null && files.length > 0) {
                    for(File f:files) {
                        if (f.isFile()){
                            boolean b = f.delete();
                            log.info("文件夹 , 删除文件是否成功="+b+" 文件名称="+f.getPath());
                        } else if(f.isDirectory()){
                            deleteFileAndDir(f.getPath());
                        }
                    }
                    boolean b = file.delete();
                    log.info("文件夹 , 删除子文件之后,删除文件夹="+b+" , 文件夹名称="+file.getPath());
                } else if(files.length == 0) {
                    boolean b = file.delete();
                    log.info("文件夹 ,子文件列表为空,删除空文件夹="+b+" , 文件夹名称="+file.getPath());
                }
            } else {
                boolean b = file.delete();
                log.info("删除文件="+b+" , 文件夹名称="+file.getPath());
            }
        }
    }
}
